package com.auto.learning.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import com.auto.learning.net.DownLoadInfo;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

/**
 * 文件工具类
 * 
 * @ClassName: FileUtil All rights Reserved, Designed By isoftStone Copyright:
 *             Copyright(C) 2013 Company: isoftStone Holdings Limited
 * @version: V1.0
 */
public class FileUtil {
	private final static String TAG = FileUtil.class.getSimpleName();

	/** SD卡文件缓存的目录 */
	private static String fileCachePath = null;
	/** 文件缓存的目录 */
	private static String tempFilePath = null;

	public static String getTempFilePath() {
		return tempFilePath;
	}

	public static String getFileCachePath() {
		return fileCachePath;
	}
	
	/**
	 * 初始化应用的临时目录
	 * 
	 * @param context
	 * @param fileName
	 */
	public static void initFileCachePath(Context context, String fileName) {
		
		File cacheDir = null;
		// 如果有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片
		// 没有SD卡就放在系统的缓存目录中
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {
			cacheDir = context.getExternalCacheDir();
		} else {
			cacheDir = context.getCacheDir();
		}
		if (cacheDir == null )
			cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), fileName);
		/**
		 * 解决转移下载目录之后文件的转移情况
		 */
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);   //判断sd卡是否存在 
		if(sdCardExist){   
			fileCachePath = Environment.getExternalStorageDirectory().getAbsolutePath() + DownLoadInfo.MAIN_ROOT;//获取跟目录 
			tempFilePath = cacheDir.getAbsolutePath();
		}else {
			fileCachePath = cacheDir.getAbsolutePath();
			tempFilePath = fileCachePath;
		}
		try {
			File tempFile = new File(fileCachePath + "/temp");
			if (!tempFile.exists()) {
				tempFile.mkdirs();
			}
			File themeFile = new File(fileCachePath + "/theme");
			if (!themeFile.exists()) {
				themeFile.mkdirs();
			}
			File cacheImageFile = new File(fileCachePath + "/cacheImage");
			if (!cacheImageFile.exists()) {
				cacheImageFile.mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		Log.d(TAG, "Cache file path:" + downloadFilePath );
	}

	/**
	 * 保存首页配置文件
	 */
	public static void saveHomeSetFile(Context context, String data) {
		initFileCachePath(context, "");
		try {
			printlnFile("home_set.xml", data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 保存bitMap到本地
	 * @param bitName
	 * @param mBitmap
	 * @return
	 * @throws IOException
	 */
	public static String saveBitmap(String bitName, Bitmap mBitmap) throws IOException {
		String mFilePath = fileCachePath + "/temp/" + bitName;
		File f = new File(mFilePath);
		if (!f.exists()) {
			f.createNewFile();
			FileOutputStream fOut = null;
			try {
				fOut = new FileOutputStream(f);
				mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
				fOut.flush();
				fOut.close();
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return mFilePath;
	}
	
	
	public static void saveHomeUserSetFile(Context context, String data) {
		initFileCachePath(context, "");
		try {
			printlnFile("userhome_set.xml", data);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
//	/**
//	 * 缓存游客菜单树
//	 * 
//	 * @param context
//	 * @param data
//	 */
//	public static void saveTouristsFuncListFile(Context context, String data) {
//		initFileCachePath(context, "");
//		try {
//			printlnFile("funclist_Tourists", data);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//	}

//	/**
//	 * 缓存用户菜单树
//	 * 
//	 * @param context
//	 * @param data
//	 */
//	public static void saveUserFuncListFile(Context context, String data) {
//		initFileCachePath(context, "");
//		try {
//			printlnFile("funclist_User", data);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//	}

	private static void printlnFile(String filename, String msg)
			throws IOException {
		File f = new File(fileCachePath, filename);
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		f.createNewFile();
		PrintWriter p = new PrintWriter(new OutputStreamWriter(
				new FileOutputStream(f), "utf-8"));
		p.println(msg);
		p.flush();
		p.close();
	}
	/**
	 * 获取用户菜单缓存
	 * @param context
	 * @return
	 */
	public String getUserFuncListFile(Context context) {
		String data = null;
		String name = "funclist_User";
		File file = new File(fileCachePath, name);

		try {
			FileInputStream in = new FileInputStream(file);
			data = readTextInputStream(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

	public static String readTextInputStream(InputStream is) throws IOException {
		StringBuffer strbuffer = new StringBuffer();
		String line;
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(is));
			while ((line = reader.readLine()) != null) {
				strbuffer.append(line);
			}
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
		return strbuffer.toString();
	}

	/**
	 * 初始化应用的临时目录
	 * 
	 * @param context
	 * @param fileName
	 */
	public static String getDatabasePath(Context context) {
		String dbpath = "/data/data/com.infinitus/Message";

		return dbpath;
	}
	
	
	public static boolean DeleteFolder(String sPath) {
		boolean flag = false;
		if (sPath != null) {
			File file = new File(sPath);
			// 判断目录或文件是否存在
			if (!file.exists()) { // 不存在返回 false
				return flag;
			} else {
				// 判断是否为文件
				if (file.isFile()) { // 为文件时调用删除文件方法
					return deleteFile(sPath);
				} else { // 为目录时调用删除目录方法
					return deleteDirectory(sPath);
				}
			}
		}
		return flag;
	}
	
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}
	
	public static boolean deleteDirectory(String sPath) {
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}
	
}
